package com.newflypig.jblog.controller;

import java.io.File;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.io.FileUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.multipart.MultipartFile;

@Controller
public class UploadController {
	
	@RequestMapping(value="/uploadfile",method=RequestMethod.POST)
	public void hello(HttpServletRequest request,HttpServletResponse response,MultipartFile attach){
		try {
			request.setCharacterEncoding( "utf-8" );
			response.setHeader( "Content-Type" , "text/html" );
			String rootPath = request.getSession().getServletContext().getRealPath("/resources/upload/");
			
			/**
			 * 文件路径不存在则需要创建文件路径
			 */
			File filePath=new File(rootPath);
			if(!filePath.exists()){
				filePath.mkdirs();
			}
						
	        //最终文件名
	        File realFile=new File(rootPath+File.separator+attach.getOriginalFilename());
	        FileUtils.copyInputStreamToFile(attach.getInputStream(), realFile);
			
			response.getWriter().write( "{\"testdata\": \"testdata\"}" );
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
}
